package com.example.demo.service.impl;

import com.example.demo.dto.WorkflowTaskTypeDTO;
import com.example.demo.dto.TaskTypeApprovalStatisticsDTO;
import com.example.demo.dto.UserApprovalStatisticsDTO;
import com.example.demo.entity.WorkflowTaskType;
import com.example.demo.entity.TaskApprovalStatus;
import com.example.demo.mapper.WorkflowTaskTypeMapper;
import com.example.demo.mapper.TaskApprovalStatusMapper;
import com.example.demo.mapper.NewTaskMapper;
import com.example.demo.mapper.DataSourceMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.WorkflowTaskTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;


@Service
public class    WorkflowTaskTypeServiceImpl implements WorkflowTaskTypeService {

    @Autowired
    private WorkflowTaskTypeMapper workflowTaskTypeMapper;
    
    @Autowired
    private TaskApprovalStatusMapper taskApprovalStatusMapper;
    
    @Autowired
    private NewTaskMapper newTaskMapper;
    
    @Autowired
    private DataSourceMapper dataSourceMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<WorkflowTaskTypeDTO> getAllWorkflowTaskTypes() {
        return workflowTaskTypeMapper.selectAll().stream()
                .map(WorkflowTaskTypeDTO::fromEntity)
                .collect(Collectors.toList());
    }

    @Override
    public WorkflowTaskTypeDTO getWorkflowTaskTypeById(Long id) {
        WorkflowTaskType workflowTaskType = workflowTaskTypeMapper.selectById(id);
        return workflowTaskType != null ? WorkflowTaskTypeDTO.fromEntity(workflowTaskType) : null;
    }

    @Override
    public List<WorkflowTaskTypeDTO> getWorkflowTaskTypesByWorkflowId(Long workflowId) {
        return workflowTaskTypeMapper.selectByWorkflowId(workflowId).stream()
                .map(WorkflowTaskTypeDTO::fromEntity)
                .collect(Collectors.toList());
    }

    @Override
    public List<WorkflowTaskTypeDTO> getWorkflowTaskTypesByTaskTypeId(Long taskTypeId) {
        return workflowTaskTypeMapper.selectByTaskTypeId(taskTypeId).stream()
                .map(WorkflowTaskTypeDTO::fromEntity)
                .collect(Collectors.toList());
    }

    @Override
    public List<WorkflowTaskTypeDTO> getWorkflowTaskTypesByDatasourceId(Long datasourceId) {
        return workflowTaskTypeMapper.selectByDatasourceId(datasourceId).stream()
                .map(WorkflowTaskTypeDTO::fromEntity)
                .collect(Collectors.toList());
    }

    @Override
    public WorkflowTaskTypeDTO createWorkflowTaskType(WorkflowTaskTypeDTO workflowTaskTypeDTO) {
        WorkflowTaskType workflowTaskType = workflowTaskTypeDTO.toEntity();
        workflowTaskType.setCreatedAt(LocalDateTime.now());
        workflowTaskType.setUpdatedAt(LocalDateTime.now());
        workflowTaskTypeMapper.insert(workflowTaskType);
        return WorkflowTaskTypeDTO.fromEntity(workflowTaskType);
    }

    @Override
    public List<WorkflowTaskTypeDTO> batchCreateWorkflowTaskTypes(List<WorkflowTaskTypeDTO> workflowTaskTypeDTOs) {
        List<WorkflowTaskType> workflowTaskTypes = workflowTaskTypeDTOs.stream()
                .map(dto -> {
                    WorkflowTaskType entity = dto.toEntity();
                    entity.setCreatedAt(LocalDateTime.now());
                    entity.setUpdatedAt(LocalDateTime.now());
                    return entity;
                })
                .collect(Collectors.toList());
        
        workflowTaskTypeMapper.batchInsert(workflowTaskTypes);
        
        return workflowTaskTypes.stream()
                .map(WorkflowTaskTypeDTO::fromEntity)
                .collect(Collectors.toList());
    }

    @Override
    public WorkflowTaskTypeDTO updateWorkflowTaskType(Long id, WorkflowTaskTypeDTO workflowTaskTypeDTO) {
        WorkflowTaskType existing = workflowTaskTypeMapper.selectById(id);
        if (existing == null) {
            return null;
        }
        
        WorkflowTaskType workflowTaskType = workflowTaskTypeDTO.toEntity();
        workflowTaskType.setId(id);
        workflowTaskType.setCreatedAt(existing.getCreatedAt());
        workflowTaskType.setUpdatedAt(LocalDateTime.now());
        workflowTaskTypeMapper.updateById(workflowTaskType);
        return WorkflowTaskTypeDTO.fromEntity(workflowTaskType);
    }

    @Override
    public void deleteWorkflowTaskType(Long id) {
        workflowTaskTypeMapper.deleteById(id);
    }

    @Override
    public void deleteWorkflowTaskTypesByWorkflowId(Long workflowId) {
        workflowTaskTypeMapper.deleteByWorkflowId(workflowId);
    }

    @Override
    public void deleteWorkflowTaskTypeByWorkflowIdAndTaskTypeId(Long workflowId, Long taskTypeId) {
        workflowTaskTypeMapper.deleteByWorkflowIdAndTaskTypeId(workflowId, taskTypeId);
    }

    @Override
    public long countWorkflowTaskTypes() {
        return workflowTaskTypeMapper.count();
    }
    
    @Override
    public TaskTypeApprovalStatisticsDTO getTaskTypeApprovalStatistics(Long taskTypeId, String version, String dep, String app) {
        //log.info("开始获取任务类型审批统计信息，任务类型ID: {}, 版本: {}, 部门: {}, 应用: {}", taskTypeId, version, dep, app);
        
        // 1. 根据任务类型ID获取工作流任务类型信息
        //log.debug("步骤1: 根据任务类型ID {} 查询工作流任务类型信息", taskTypeId);
        List<WorkflowTaskType> workflowTaskTypes = workflowTaskTypeMapper.selectByTaskTypeId(taskTypeId);
        if (workflowTaskTypes.isEmpty()) {
            //log.warn("未找到任务类型ID为 {} 的工作流任务类型", taskTypeId);
            throw new RuntimeException("未找到任务类型ID为 " + taskTypeId + " 的工作流任务类型");
        }
        //log.debug("找到 {} 个工作流任务类型记录", workflowTaskTypes.size());
        
        // 2. 获取数据源ID
        Long dataSourceId = workflowTaskTypes.get(0).getDatasourceId();
        //log.debug("步骤2: 获取到数据源ID: {}", dataSourceId);
        
        // 3. 根据数据源ID、版本、部门和应用信息查询任务ID
        //log.debug("步骤3: 根据数据源ID {} 和查询条件(版本: {}, 部门: {}, 应用: {}) 查询任务ID", dataSourceId, version, dep, app);
        List<Long> taskIds = getTaskIdsByDataSourceAndCriteria(dataSourceId, version, dep, app);
        //log.debug("查询到 {} 个任务ID", taskIds.size());
        
        // 4. 根据任务ID获取审批信息
        //log.debug("步骤4: 根据任务ID列表查询审批状态信息");
        List<TaskApprovalStatus> approvalStatuses = new ArrayList<>();
        for (Long taskId : taskIds) {
            List<TaskApprovalStatus> statuses = taskApprovalStatusMapper.selectByTaskId(taskId);
            approvalStatuses.addAll(statuses);
            //log.trace("任务ID {} 包含 {} 条审批状态记录", taskId, statuses.size());
        }
        //log.debug("总共获取到 {} 条审批状态记录", approvalStatuses.size());
        
        // 5. 统计审批信息
        //log.debug("步骤5: 统计审批信息");
        TaskTypeApprovalStatisticsDTO statistics = new TaskTypeApprovalStatisticsDTO();
        statistics.setTaskTypeId(taskTypeId);
        statistics.setTaskTypeName(workflowTaskTypes.get(0).getTaskTypeName());
        statistics.setDataSourceId(dataSourceId);
        
        // 获取数据源名称
        //log.trace("获取数据源ID {} 的名称信息", dataSourceId);
        com.example.demo.entity.DataSource dataSource = dataSourceMapper.selectById(dataSourceId);
        if (dataSource != null) {
            statistics.setDataSourceName(dataSource.getName());
            //log.trace("数据源名称: {}", dataSource.getName());
        } else {
            //log.warn("未找到数据源ID {} 的信息", dataSourceId);
        }
        
        // 统计任务状态
        //log.trace("统计各状态的任务数量");
        int totalTasks = approvalStatuses.size();
        int completedTasks = (int) approvalStatuses.stream()
                .filter(status -> status.getStatus() != null && status.getStatus() == 2)
                .count();
        int pendingTasks = (int) approvalStatuses.stream()
                .filter(status -> status.getStatus() != null && status.getStatus() == 0)
                .count();
        int processingTasks = (int) approvalStatuses.stream()
                .filter(status -> status.getStatus() != null && status.getStatus() == 1)
                .count();
        int rejectedTasks = (int) approvalStatuses.stream()
                .filter(status -> status.getStatus() != null && status.getStatus() == 3)
                .count();
        int skippedTasks = (int) approvalStatuses.stream()
                .filter(status -> status.getStatus() != null && status.getStatus() == 4)
                .count();
        
        statistics.setTotalTasks(totalTasks);
        statistics.setCompletedTasks(completedTasks);
        statistics.setPendingTasks(pendingTasks);
        statistics.setProcessingTasks(processingTasks);
        statistics.setRejectedTasks(rejectedTasks);
        statistics.setSkippedTasks(skippedTasks);
        
        //log.debug("任务统计结果 - 总数: {}, 已完成: {}, 待处理: {}, 处理中: {}, 已拒绝: {}, 已跳过: {}", 
                //totalTasks, completedTasks, pendingTasks, processingTasks, rejectedTasks, skippedTasks);
        
        // 6. 按审批人统计信息
        //log.debug("步骤6: 按审批人统计信息");
        Map<Long, List<TaskApprovalStatus>> statusesByApprover = approvalStatuses.stream()
                .filter(status -> status.getApproverId() != null)
                .collect(Collectors.groupingBy(TaskApprovalStatus::getApproverId));
        
        List<UserApprovalStatisticsDTO> approverStatistics = statusesByApprover.entrySet().stream()
                .map(entry -> {
                    Long approverId = entry.getKey();
                    List<TaskApprovalStatus> approverStatuses = entry.getValue();
                    
                    UserApprovalStatisticsDTO userStat = new UserApprovalStatisticsDTO();
                    userStat.setUserId(approverId);
                    
                    // 获取审批人姓名（需要UserMapper支持）
                    // 从User表获取真实的用户名和authId
                    com.example.demo.entity.User user = userMapper.selectById(approverId.intValue());
                    if (user != null) {
                        userStat.setUserName(user.getUserName());
                        userStat.setUserAuthId(user.getAuthId());
                    } else {
                        // 如果未找到用户，使用默认值
                        userStat.setUserName("未知用户(" + approverId + ")");
                        userStat.setUserAuthId("unknown_" + approverId);
                    }
                    
                    // 统计该审批人的任务状态
                    int userTotalTasks = approverStatuses.size();
                    int userCompletedTasks = (int) approverStatuses.stream()
                            .filter(status -> status.getStatus() != null && status.getStatus() == 2)
                            .count();
                    int userPendingTasks = (int) approverStatuses.stream()
                            .filter(status -> status.getStatus() != null && status.getStatus() == 0)
                            .count();
                    int userProcessingTasks = (int) approverStatuses.stream()
                            .filter(status -> status.getStatus() != null && status.getStatus() == 1)
                            .count();
                    
                    userStat.setTotalTasks(userTotalTasks);
                    userStat.setCompletedTasks(userCompletedTasks);
                    userStat.setPendingTasks(userPendingTasks);
                    userStat.setProcessingTasks(userProcessingTasks);
                    
                    //log.trace("审批人ID {} 的统计信息 - 总任务数: {}, 已完成: {}, 待处理: {}, 处理中: {}", 
                            //approverId, userTotalTasks, userCompletedTasks, userPendingTasks, userProcessingTasks);
                    
                    return userStat;
                })
                .collect(Collectors.toList());
        
        statistics.setApproverStatistics(approverStatistics);
        //log.debug("总共统计了 {} 个审批人的信息", approverStatistics.size());
        
        //log.info("任务类型审批统计信息获取完成，任务类型ID: {}, 数据源ID: {}, 总任务数: {}", 
                //taskTypeId, dataSourceId, totalTasks);
        
        return statistics;
    }
    
    @Override
    public List<TaskTypeApprovalStatisticsDTO> getWorkflowApprovalStatistics(Long workflowId, String version, String dep, String app) {
        //log.info("开始获取工作流审批统计信息，工作流ID: {}, 版本: {}, 部门: {}, 应用: {}", workflowId, version, dep, app);
        
        // 1. 根据工作流ID获取所有相关的任务类型ID
        //log.debug("步骤1: 根据工作流ID {} 查询相关的流程任务映射", workflowId);
        List<WorkflowTaskType> workflowTaskTypes = workflowTaskTypeMapper.selectByWorkflowId(workflowId);
        if (workflowTaskTypes.isEmpty()) {
            //log.warn("未找到工作流ID为 {} 的流程任务映射", workflowId);
            return new ArrayList<>();
        }
        //log.debug("找到 {} 个流程任务映射记录", workflowTaskTypes.size());
        
        // 2. 提取唯一的任务类型ID列表
        List<Long> taskTypeIds = workflowTaskTypes.stream()
                .map(WorkflowTaskType::getTaskTypeId)
                .distinct()
                .collect(Collectors.toList());
        //log.debug("提取到 {} 个唯一的任务类型ID: {}", taskTypeIds.size(), taskTypeIds);
        
        // 3. 为每个任务类型ID调用统计方法
        //log.debug("步骤2: 为每个任务类型ID获取审批统计信息");
        List<TaskTypeApprovalStatisticsDTO> statisticsList = new ArrayList<>();
        for (Long taskTypeId : taskTypeIds) {
            try {
                //log.debug("获取任务类型ID {} 的审批统计信息", taskTypeId);
                TaskTypeApprovalStatisticsDTO statistics = getTaskTypeApprovalStatistics(taskTypeId, version, dep, app);
                statisticsList.add(statistics);
                //log.debug("任务类型ID {} 的审批统计信息获取成功", taskTypeId);
            } catch (Exception e) {
                //log.error("获取任务类型ID {} 的审批统计信息时发生错误: {}", taskTypeId, e.getMessage(), e);
                // 继续处理其他任务类型，不中断整个流程
            }
        }
        
        //log.info("工作流审批统计信息获取完成，工作流ID: {}, 共获取到 {} 个任务类型的统计信息", workflowId, statisticsList.size());
        return statisticsList;
    }
    
    /**
     * 根据数据源ID和查询条件获取任务ID列表
     * 支持版本、部门和应用的查询条件
     */
    private List<Long> getTaskIdsByDataSourceAndCriteria(Long dataSourceId, String version, String dep, String app) {
        //log.debug("根据数据源ID {} 和查询条件(版本: {}, 部门: {}, 应用: {}) 获取任务ID列表", dataSourceId, version, dep, app);
        
        // 构建查询参数
        Map<String, Object> searchParams = new HashMap<>();
        if (version != null && !version.isEmpty()) {
            searchParams.put("version", version);
        }
        if (dep != null && !dep.isEmpty()) {
            searchParams.put("dep", dep);
        }
        if (app != null && !app.isEmpty()) {
            searchParams.put("app", app);
        }
        
        // 使用searchTasks方法查询符合条件的任务
        List<com.example.demo.entity.NewTask> tasks = newTaskMapper.searchTasks(0, 1000, dataSourceId, null, searchParams);
        
        // 提取任务ID
        List<Long> taskIds = tasks.stream()
                .map(com.example.demo.entity.NewTask::getId)
                .collect(Collectors.toList());
        
        //log.trace("从数据源ID {} 根据查询条件获取到 {} 个任务ID", dataSourceId, taskIds.size());
        return taskIds;
    }
}